package com.elephant.core.utils.sqlit;

import java.sql.*;

/**
 * @author hai
 * @description
 * @date 14:00 2018/9/29
 */
public class SqlitUtil {

    private static final String Class_Name = "org.sqlite.JDBC";
    private static final String DB_URL = "jdbc:sqlite:D:\\xiaozhan\\dictionary.db";

    public static void main(String args[]) {
        // load the sqlite-JDBC driver using the current class loader
        Connection connection = null;
        try {
            connection = createConnection();
            func1("select * from t_dictionary limit 10",connection);
            System.out.println("Success!");
        }  catch (SQLException e) {
            System.err.println(e.getMessage());
        } catch(Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if (connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                // connection close failed.
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建Sqlite数据库连接
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public static Connection createConnection() throws SQLException, ClassNotFoundException {
        Class.forName(Class_Name);
        return DriverManager.getConnection(DB_URL);
    }

    public static ResultSet func1(String sql, Connection connection) throws SQLException {
        Statement statement = connection.createStatement();
        // set timeout to 30 sec.
        statement.setQueryTimeout(30);
        // 执行查询语句
        ResultSet rs = statement.executeQuery(sql);
        /*while (rs.next()) {
            String col1 = rs.getString("trans");
            System.out.println("col1 = " + col1);
        }*/
        return rs;
    }


    public static void execute(String sql, Connection connection) throws SQLException {
        try{
            Statement statement = connection.createStatement();
            statement.setQueryTimeout(30);
            statement.execute(sql);
        }catch (Exception e){
            System.out.println("error " + sql);
        }
    }
}
